package cn.gp.chat.service;

import cn.gp.chat.commom.res.LoginRequest;
import cn.gp.chat.commom.res.RegisterRequest;
import cn.gp.chat.commom.res.UpdateProfileRequest;
import cn.gp.chat.commom.resp.FriendRequestVo;
import cn.gp.chat.commom.resp.UserVo;
import cn.gp.chat.entity.User;
import cn.gp.chat.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserMapper userMapper;
    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    public UserVo login(LoginRequest request) {
        // 1. 查询用户
        User user = userMapper.selectByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 密码比对
        if (!request.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 3. 查询好友列表
        List<UserVo.FriendVo> friends = userMapper.selectFriendsByUserId(user.getId());

        // 4. 返回用户信息（包括好友列表）
        return new UserVo(
                user.getId(),
                user.getUsername(),
                user.getNickname(),
                user.getAvatar(),
                user.getStatus(),
                friends
        );
    }

    public UserVo register(RegisterRequest request) {
        // 1. 检查用户名是否已存在
        if (userMapper.existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 2. 构建用户实体
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword()); // 明文存储
        user.setNickname(request.getNickname());

        // 3. 插入数据库
        userMapper.insert(user);

        // 4. 返回注册结果
        return new UserVo(user.getId(), user.getUsername(), user.getNickname(), user.getAvatar(), 0, null);
    }

    public UserVo updateProfile(UpdateProfileRequest request) {
        User user = userMapper.findById(request.getId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新用户信息
        user.setNickname(request.getNickname());
        user.setAvatar(request.getAvatar());
        userMapper.updateProfile(user);

        // 查询好友列表
        List<UserVo.FriendVo> friends = userMapper.selectFriendsByUserId(user.getId());
        
        // 返回更新后的用户信息
        return new UserVo(
                user.getId(),
                user.getUsername(),
                user.getNickname(),
                user.getAvatar(),
                user.getStatus(),
                friends
        );
    }

    public List<UserVo> searchUsers(String keyword) {
        // 1. 参数校验
        if (keyword == null || keyword.trim().isEmpty()) {
            throw new RuntimeException("搜索关键词不能为空");
        }

        // 2. 搜索用户
        List<User> users = userMapper.searchUsers(keyword);
        
        // 3. 转换为VO对象
        return users.stream()
                .map(user -> new UserVo(
                        user.getId(),
                        user.getUsername(),
                        user.getNickname(),
                        user.getAvatar(),
                        user.getStatus(),
                        null // 搜索结果不包含好友列表
                ))
                .toList();
    }

    /**
     * @Param senderId
     * @Param receiverId
     * @Param message
     * @Return void
     * @Description TODO
     * @Author He Guoping
     * @Date 2025/6/19 10:00
     */
    @Transactional
    public void sendFriendRequest(Long senderId, Long receiverId, String message) {
        // 1. 检查发送者是否存在
        User sender = userMapper.findById(senderId);
        if (sender == null) {
            throw new RuntimeException("发送者不存在");
        }

        // 2. 检查接收者是否存在
        User receiver = userMapper.findById(receiverId);
        if (receiver == null) {
            throw new RuntimeException("接收者不存在");
        }

        // 3. 检查是否已经是好友
        if (userMapper.existsFriendship(senderId, receiverId)) {
            throw new RuntimeException("已经是好友关系");
        }

        // 4. 检查是否已经发送过请求
        if (userMapper.existsFriendRequest(senderId, receiverId)) {
            throw new RuntimeException("已经发送过好友请求");
        }

        // 5. 创建好友请求
        userMapper.insertFriendRequest(senderId, receiverId, message);
    }

    public List<FriendRequestVo> getFriendRequests(Long userId) {
        // 1. 获取当前用户的好友请求列表
        List<FriendRequestVo> requests = userMapper.selectFriendRequests(userId);
        
        // 2. 补充请求者信息
        for (FriendRequestVo request : requests) {
            log.info("处理好友请求: id={}, requesterId={}, receiverId={}, message={}", 
                request.getId(), request.getRequesterId(), request.getReceiverId(), request.getRequestMessage());
            
            if (request.getRequesterId() == null) {
                log.error("好友请求数据异常: requesterId为null, requestId={}", request.getId());
                continue;
            }
            
            User requester = userMapper.findById(request.getRequesterId());
            if (requester != null) {
                UserVo requesterInfo = new UserVo(
                    requester.getId(),
                    requester.getUsername(),
                    requester.getNickname(),
                    requester.getAvatar(),
                    requester.getStatus(),
                    null
                );
                request.setRequesterInfo(requesterInfo);
                log.info("已设置请求者信息: requesterId={}, username={}", 
                    requester.getId(), requester.getUsername());
            } else {
                log.warn("找不到请求者信息: requesterId={}", request.getRequesterId());
            }
        }
        
        return requests;
    }

    /**
     * @Param userId
     * @Param requestId
     * @Param status
     * @Return void
     * @Description 处理好友请求 遇到任何异常 都需回滚
     * @Author He Guoping
     * @Date 2025/6/19 10:02
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleFriendRequest(Long userId, Long requestId, Integer status) {
        // 参数校验
        if (userId == null || requestId == null || status == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 获取好友请求
        FriendRequestVo request = userMapper.selectFriendRequestById(requestId);
        if (request == null) {
            log.error("好友请求不存在: requestId={}", requestId);
            throw new IllegalArgumentException("好友请求不存在");
        }
        
        // 验证接收者身份
        if (request.getReceiverId() == null) {
            log.error("好友请求数据异常: receiverId为null, requestId={}", requestId);
            throw new IllegalArgumentException("好友请求数据异常");
        }
        
        if (!userId.equals(request.getReceiverId())) {
            log.error("无权处理此好友请求: userId={}, requestId={}, receiverId={}", 
                userId, requestId, request.getReceiverId());
            throw new IllegalArgumentException("无权处理此好友请求");
        }
        
        // 验证请求状态
        if (request.getStatus() != 0) {
            log.warn("该请求已被处理: requestId={}, status={}", requestId, request.getStatus());
            throw new IllegalArgumentException("该请求已被处理");
        }
        
        try {
            // 更新请求状态
            userMapper.updateFriendRequestStatus(requestId, status);
            
            // 如果同意请求，添加好友关系
            if (status == 1) {
                // 添加双向好友关系
                userMapper.insertFriendship(request.getRequesterId(), request.getReceiverId());
                userMapper.insertFriendship(request.getReceiverId(), request.getRequesterId());
                log.info("已建立好友关系: userId1={}, userId2={}", 
                    request.getRequesterId(), request.getReceiverId());
            }
        } catch (Exception e) {
            log.error("处理好友请求失败: requestId={}, status={}, error={}", 
                requestId, status, e.getMessage());
            throw new RuntimeException("处理好友请求失败", e);
        }
    }

    /**
     * @Param userId
     * @Return cn.gp.chat.commom.resp.UserVo
     * @Description TODO
     * @Author He Guoping
     * @Date 2025/6/19 10:03
     */
    public UserVo getCurrentUser(Long userId) {
        // 1. 查询用户
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 查询好友列表
        List<UserVo.FriendVo> friends = userMapper.selectFriendsByUserId(userId);

        // 3. 返回用户信息（包括好友列表）
        return new UserVo(
                user.getId(),
                user.getUsername(),
                user.getNickname(),
                user.getAvatar(),
                user.getStatus(),
                friends
        );
    }
}